package com.idgenerator.configuration;

import com.idgenerator.IdGeneratorService;
import com.idgenerator.generator.IdGenerator;
import com.idgenerator.generator.LocalIdGenerator;
import com.idgenerator.generator.ZookeeperIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * ID生成器
 */
@Slf4j
@Configuration
@ConditionalOnMissingBean(IdGeneratorService.class)
public class IdGeneratorAutoConfiguration {

    @Autowired
    private IdGeneratorProperties idGeneratorProperties;

    /**
     * 本地生成ID
     */
    @Bean
    public List<LocalIdGenerator> localIdGenerator() {
        return idGeneratorProperties.getLocal().stream().filter(localIdGen -> localIdGen.getEnable()).map(local -> {
            log.info("加载本地ID生成器：{}", local);
            LocalIdGenerator localIdGenerator = new LocalIdGenerator(local.getDataCenterId(), local.getWorkerId());
            localIdGenerator.setGen(local.getGen());
            return localIdGenerator;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    /**
     * zookeeper生成ID
     */
    @Bean
    @ConditionalOnClass(name = "org.apache.curator.framework.CuratorFramework")
    public List<ZookeeperIdGenerator> zookeeperIdGenerator() {
        return idGeneratorProperties.getZookeeper().stream().filter(zk -> zk.getEnable()).map(zk -> {
            log.info("加载Zookeeper ID生成器：{}", zk);
            ZookeeperIdGenerator zookeeperIdGenerator = new ZookeeperIdGenerator(zk.getConnectionString(), zk.getPort(),zk.getName());
            zookeeperIdGenerator.setGen(zk.getGen());
            return zookeeperIdGenerator;
        }).filter(Objects::nonNull).collect(Collectors.toList());

    }

    /**
     * Id生成器服务
     */
    @Bean
    public IdGeneratorService idGeneratorService(IdGeneratorProperties idGeneratorProperties,
                                                 List<List<? extends IdGenerator>> idGeneratorList
    ) {
        IdGeneratorService service = new IdGeneratorService();
        service.setIdGeneratorList(idGeneratorList);
        service.setIdGeneratorProperties(idGeneratorProperties);
        return service;
    }


}
